package com.ygqh.baby.controller.mobile;

import com.alibaba.fastjson.JSON;
import com.ygqh.baby.ao.Message;
import com.ygqh.baby.ao.QueryInfo;
import com.ygqh.baby.ao.ResponseEntity;
import com.ygqh.baby.ao.ReturnReasonType;
import com.ygqh.baby.handler.ReturnPriceHandler;
import com.ygqh.baby.model.*;
import com.ygqh.baby.po.*;
import com.ygqh.baby.service.YgReturnOrderLogService;
import com.ygqh.baby.service.YgReturnOrderService;
import com.ygqh.baby.service.YgSkuService;
import com.ygqh.baby.service.impl.DocumentConstant;
import com.ygqh.baby.utils.DateConvertUtils;
import com.ygqh.baby.utils.JsonUtils;
import com.ygqh.baby.utils.SessionUtil;
import com.ygqh.baby.utils.ThreadPool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 退货相关
 *
 * @author guohao
 */
@Controller
@RequestMapping("/app/return")
public class YgReturnOrderController extends BaseController {

    @Autowired
    private DocumentConstant documentConstant;
    @Autowired
    private YgReturnOrderService ygReturnOrderService;
    @Autowired
    private YgReturnOrderLogService ygReturnOrderLogService;
    @Autowired
    private YgSkuService skuService;
    @Autowired
    private ThreadPool threadPool;
    @Autowired
    private ReturnPriceHandler returnPriceHandler;

    /**
     * 获取可退换货订单列表
     *
     * @param queryInfo
     * @return
     */
    @RequestMapping(value = "findOrderListForReturn")
    @ResponseBody
    public ResponseEntity findOrderListForReturn(QueryInfo queryInfo) {
        YgUser user = SessionUtil.getCurrentUser();
        List<YgOrderModel> list = ygReturnOrderService.findOrderListForReturn(queryInfo, user.getId(), PLATFORM_NO);
        return ResponseEntity.success(list);


    }

    /**
     * 获取退换货订单列表
     *
     * @param queryInfo
     * @return
     */
    @RequestMapping(value = "findReturnList")
    @ResponseBody
    public ResponseEntity findReturnList(QueryInfo queryInfo) {
        YgUser user = SessionUtil.getCurrentUser();

        List<YgReturnOrderModel> list = ygReturnOrderService.findReturnList(queryInfo, user.getId(), PLATFORM_NO);

        return ResponseEntity.success(list);

    }

    /**
     * 获取商品详细用于订单退换货
     *
     * @param orderId
     * @return
     */
    @RequestMapping(value = "findOrderInfo4Retrun")
    @ResponseBody
    public ResponseEntity findOrderInfo4Retrun(Long orderId) {
        YgUser user = SessionUtil.getCurrentUser();
        YgOrderInfoModel model = ygReturnOrderService.findOrderInfo4Retrun(orderId, user.getId());
        return ResponseEntity.success(model);

    }

    /**
     * 获取退换货进度
     *
     * @param returnCode
     * @return
     */
    @RequestMapping(value = "getReturnScheduleList")
    @ResponseBody
    public ResponseEntity getReturnScheduleList(String returnCode) {
        List<YgReturnOrderLog> list = ygReturnOrderLogService.getReturnScheduleList(returnCode);

        return ResponseEntity.success(list);

    }

    /**
     * 获取退货金额
     *
     * @param returnInfo
     * @return
     */
    @RequestMapping(value = "getReturnPrice")
    @ResponseBody
    public ResponseEntity getReturnPrices(String returnInfo) {
        YgReturnInfoModel infoModel = JsonUtils.toObject(returnInfo, YgReturnInfoModel.class);
        Message msg = returnPriceHandler.getReturnPrice(infoModel);
        return ResponseEntity.converter(msg);
    }

    /**
     * 保存退货单
     *
     * @param returnInfo
     * @param returnReason
     * @param imgPaths
     * @return
     */
    @RequestMapping(value = "saveReturnOrder")
    @ResponseBody
    public ResponseEntity saveReturnOrder(String returnInfo, ReturnReasonType returnReasonType, String returnReason,
                                          String imgPaths) {
        YgUser user = SessionUtil.getCurrentUser();
        if (returnReasonType == null) {
            return ResponseEntity.error("请选择退换货原因。", null);
        }

        YgReturnInfoModel infoModel = JsonUtils.toObject(returnInfo, YgReturnInfoModel.class);
        Message msg = returnPriceHandler.getReturnPrice(infoModel);
        if (msg.getType().equals(Message.Type.error)) {
            return ResponseEntity.converter(msg);
        }
        YgReturnInfoModel info = (YgReturnInfoModel) msg.getExtra();
        Message message = ygReturnOrderService.saveReturnOrder(infoModel, returnReasonType, returnReason,
                imgPaths, info, user.getId());
        Map<String, Object> map = new HashMap<>();
        if (message.getType().equals(Message.Type.success)) {
            String returnCode = message.getExtra().toString();
            map.put("returnCode", returnCode);
            threadPool.getExecutorService().execute(() ->
                    ygReturnOrderService.autoAuditReturnOrder(returnCode, "system", "", true));
        }
        map.put("applyTime", DateConvertUtils.format(new Date()));
        message.setExtra(map);
        return ResponseEntity.converter(message);
    }

    /**
     * 获取退换货单详细
     *
     * @param returnCode
     * @return
     */
    @RequestMapping(value = "findReturnOrderInfo")
    @ResponseBody
    public ResponseEntity findReturnOrderInfo(String returnCode) {
        YgUser user = SessionUtil.getCurrentUser();
        YgReturnOrderInfoModel orderInfo = ygReturnOrderService.findReturnOrderInfo(returnCode, user.getId());
        return ResponseEntity.success(orderInfo);
    }

    /**
     * 根据productId获取有库存的SKU列表
     *
     * @param productId
     * @param sizeName
     * @return
     */
    @RequestMapping(value = "selectWithStock")
    @ResponseBody
    public ResponseEntity selectWithStock(@RequestParam Long productId, String sizeName) {
        List<YgSku> skus = skuService.selectWithStock(productId, sizeName);
        return ResponseEntity.success(skus);
    }

    /**
     * 创建换货单
     *
     * @param exchangeOrder
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "createExchangeOrder")
    @ResponseBody
    public ResponseEntity createExchangeOrder(@RequestParam String exchangeOrder) throws Exception {
        YgExchangeOrder eOrder = JSON.parseObject(exchangeOrder, YgExchangeOrder.class);
        Message message = ygReturnOrderService.createExchangeOrder(eOrder, SessionUtil.getCurrentUser().getId());

        if (message.getType().equals(Message.Type.success)) {

            threadPool.getExecutorService().execute(new Runnable() {
                @Override
                public void run() {

                    ygReturnOrderService.autoAuditReturnOrder((String) message.getExtra(), "system", "", true);
                }
            });
        }
        String returnCode = (String) message.getExtra();
        Map<String, Object> map = new HashMap<>();
        map.put("returnCode", returnCode);
        map.put("applyTime", DateConvertUtils.format(new Date()));
        message.setExtra(map);
        return ResponseEntity.converter(message);
    }

    /**
     * 取消换货单
     *
     * @param id
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "cancelReturnOrder")
    @ResponseBody
    public ResponseEntity cancelReturnOrder(@RequestParam Long id) throws Exception {
        Long userId = SessionUtil.getCurrentUser().getId();
        Message message = ygReturnOrderService.cancelReturnOrder(id, userId);
        return ResponseEntity.converter(message);
    }

    /**
     * 更新物流信息
     *
     * @param orderLogisticsModel
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "updateLogistics")
    @ResponseBody
    public ResponseEntity updateLogistics(@RequestParam String orderLogisticsModel) throws Exception {
        YgReturnOrderLogisticsModel orderLogistics = JSON.parseObject(orderLogisticsModel, YgReturnOrderLogisticsModel.class);
        Message message = ygReturnOrderService.updateLogistics(orderLogistics, SessionUtil.getCurrentUser().getId());
        return ResponseEntity.converter(message);
    }

    /**
     * 根据订单获取物流信息
     *
     * @param returnOrderId
     * @return
     */
    @RequestMapping(value = "findReturnLogistics")
    @ResponseBody
    public ResponseEntity findReturnLogistics(@RequestParam String returnOrderId) {
        YgReturnOrder ygReturnOrder = ygReturnOrderService.findDetailByReCode(returnOrderId);
        YgSupplier ygSupplier = ygReturnOrderService.findSupplierByReturnOrder(ygReturnOrder);
        return ResponseEntity.success(ygSupplier);

    }
}
